package com.yanyu.space.common.core.util;

import cn.hutool.core.io.IoUtil;
import com.yanyu.space.common.core.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author yanyu
 */
@Slf4j
public class FileUtil {

    /**
     * byte转换成MultipartFile失败
     *
     * @param buffer   文件内容
     * @param fileName 文件名，如：test.jpg
     * @param fileType 文件类型， 如：jpg
     */
    public static MultipartFile byteToMultipartFile(byte[] buffer, String fileName, String fileType) {
        if (StringUtils.isBlank(StringUtils.substringAfterLast(fileName, "."))) {
            fileName = StringUtils.join(fileName, ".", StringUtils.substringAfterLast(fileType, "/"));
        }
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem("textField", fileType, true, fileName);
        try {
            IoUtil.write(item.getOutputStream(), true, buffer);
            MultipartFile multipartFile = new CommonsMultipartFile(item);
            return multipartFile;
        } catch (IOException e) {
            log.error("byte转换成MultipartFile失败 {}", e.getMessage(), e);
            throw new ServiceException();
        }
    }

    /**
     * byte转换成MultipartFile失败
     *
     * @param file     文件信息
     * @param fileType 文件类型， 如：jpg
     */
    public static MultipartFile fileToMultipartFile(File file, String fileType) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem("textField", fileType, true, file.getName());
        try (FileInputStream inputStream = new FileInputStream(file); OutputStream outputStream = item.getOutputStream()) {

            IoUtil.copy(inputStream, outputStream, 1024 * 5);
            MultipartFile multipartFile = new CommonsMultipartFile(item);
            return multipartFile;
        } catch (IOException e) {
            log.error("byte转换成MultipartFile失败 {}", e.getMessage(), e);
            throw new ServiceException();
        }
    }

    public static void file() {
    }
}
